<template>
  <view class="wrap view-container">
    <u-form :model="form" label-width="126px" class="form" ref="form" :rules="rules">
      <u-form-item label="标题" prop="title" :required="true" label-position="top">
        <div class="form-col-12">
          <u-input
            v-model="form.title"
            type="text" class="u-input" :disabled="!isEditDisable" :clearable="false" />
        </div>
      </u-form-item>
      <u-form-item label="编号" prop="orderNumber" :required="true" label-position="top">
        <div class="form-col-12">
          <u-input
            v-model="form.orderNumber"
            type="text" class="u-input" :disabled="true" :clearable="false" />
        </div>
      </u-form-item>
      <u-form-item label="类型" prop="type" :required="true" label-position="top">
        <div class="form-col-12">
          <uni-data-select
            v-model="form.type"
            :localdata="typeList"
						 :disabled="!isEditDisable"
            :clear="false"
          ></uni-data-select>
        </div>
      </u-form-item>
      <u-form-item label="优先级" prop="priority" :required="true" label-position="top">
        <div class="form-col-12">
          <uni-data-select
            v-model="form.priority"
            :localdata="priorityList"
						 :disabled="!isEditDisable"
            :clear="false"
          ></uni-data-select>
        </div>
      </u-form-item>
      <u-form-item label="描述" prop="description" label-position="top">
        <div class="form-col-12">
          <u-input
            v-model="form.description"
            type="textarea" class="u-input" :clearable="false" :disabled="!isEditDisable" placeholder="请输入" />
        </div>
      </u-form-item>
      <u-form-item label="发布日期" prop="createTime" label-position="top">
        <div class="form-col-12">
          <uni-datetime-picker
            v-model="form.createTime"
            type="datetime"
						:disabled="true"
            :clearable="false"
          />
        </div>
      </u-form-item>
      <u-form-item label="照片" label-position="top" class="form-item-image">
        <uni-file-picker
          :value="form.imageList"
          :limit="5" title=""
          file-mediatype="image"
          @select="handleUploadImage"
          @delete="handleDeleteImage"
          :readonly="true"></uni-file-picker>
      </u-form-item>
    </u-form>
    <div v-if="isEdit" class="footer-fixed footer-btns-edit">
      <u-button @click="handleSubmit" class="btn-submit" type="primary">提交</u-button>
      <u-button @click="handleCancel" class="btn-submit" type="info">取消</u-button>
    </div>
    <div v-else class="footer-fixed">
      <u-button @click="handleReceive" class="btn-submit" type="primary">接单</u-button>
    </div>
  </view>
</template>

<script>
import { strer, dater } from '@daelui/dogjs/dist/components.js'
import uniFiler from '@/components/libs/uni-filer.js'
import { compress } from '@/api/service/imager.js'
import dictSer from '@/api/service/dict-service.js'
import ebus from '@/components/libs/ebus.js'
import woSer from '@/api/work-order/work-order.js'

export default {
  data () {
    return {
      isEditDisable: false, // 是否禁用编辑
      isEdit: false, // 是否编辑模式
      form: {
        title: '',
        orderNumber: '',
        type: '1',
        priority: '1',
        description: '',
        createTime: '',
        imageList: []
      },
      rules: {},
			typeList: [], // 类型列表
      priorityList: [], // 优先级列表
      isShowMotto: false
    }
  },

  onLoad (params) {
    this.initView(params)
  },

  methods: {
    // 初始化视图
    initView (params) {
			// 添加
			if (params.insert) {
				this.form = {
					title: '',
					orderNumber: dater.format(Date.now(), 'yyyymmdd') + strer.uchar(8).toUpperCase(),
					type: '1',
					priority: '1',
					description: '',
					createTime: dater.format(Date.now())
				}
				this.isEdit = true
				this.isEditDisable = true
			} else {
				// 取数据
				woSer.queryItem({ id: params.id }).then(res => {
				  if (res.status === 200) {
				    let data = res.data || {}
				    let images = data.images
				    if (images) {
				    	data.imageList = images.split(',').map(item => {
				    		return {
				    			name: item,
				    			url: this.vuex_config.baseUrl + item
				    		}
				    	})
				    }
				    this.form = data
				  }
				})
			}
      // 类型列表
      this.typeList = dictSer.queryList('workOrderType')
      // 优先级列表
      this.priorityList = dictSer.queryList('workOrderPriority')
    },
    // 上传图片
    handleUploadImage (args) {
      let imageList = [...this.form.imageList]
      this.form.imageList = imageList
      let user = this.getCurrentUser() || {}
      args.tempFilePaths.forEach((path, i) => {
        let node = args.tempFiles[i].file
        // 压缩
        compress({ src: path, quality: 80 }).then((text) => {
          uniFiler.base64ToPath(text).then(path => {
            let image = {
              id: strer.udigit(),
              name: node.name,
              saveName: node.name,
              path: path,
              url: path,
              createUserId: user.userId,
              isInsert: 1
            }
            this.form.imageList.push(image)
          })
        })
      })
    },
    // 删除图片
    handleDeleteImage (args) {
      let node = args.tempFile
      let id = node.id
      // 本地添加的图片直接删除
      this.form.imageList = this.form.imageList.filter(function(item){
        if (String(item.id) === String(id)) {
          // 删除项标记
          item.isDelete = 1
          // 刚添加的则直接删除
          if (item.isInsert) {
            return false
          }
        }
        return true
      })
    },
    // 提交
    handleSubmit () {
      this.$refs.form.rules = this.rules
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }
				let user = this.getCurrentUser()
				this.form.createUserId = user.userId
				this.form.id = strer.udigit()
				this.form.status = '1'
				woSer.insert(this.form).then((res) => {
					if (res && res.status) {
						this.$u.toast('创建成功')
						setTimeout(() => {
							this.goBack()
						}, 1000)
					} else {
						this.$u.toast('创建失败')
					}
				}).catch(e => {
					console.log(e)
					this.$u.toast('创建失败')
				})
      })
    },
		// 取消
		handleCancel () {
			this.goBack()
		},
		// 接单
		handleReceive () {
      this.$refs.form.rules = this.rules
      this.$refs.form.validate(valid => {
        if (!valid) {
          return false
        }
				let user = this.getCurrentUser()
				this.form.ownerId = user.userId
				this.form.status = '2'
				woSer.update(this.form, { id: this.form.id }).then(() => {
					uni.showModal({
						title: '提示',
						content: '接单成功，是否继续抢单?',
						confirmText: '继续',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								this.goBack()
							} else {
								uni.navigateTo({
									url: '/pages/work-order/index'
								})
							}
						}
					})
				}).catch(e => {
					this.$u.toast('抢单失败')
					setTimeout(() => {
						this.goBack()
					}, 1000)
				})
      })
		}
  }
}
</script>

<style lang="less">
.view-container {
  padding-bottom: 80px;
}
.form-item-image /deep/ .u-form-item--left__content__label {
  align-items: center;
  &:after {
    content: "(最多5张)";
    color: #999;
    font-size: 12px;
    line-height: 12px;
  }
}
.footer-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 12px;
  background: #fff;
  border-top: 1px #ebeef5 solid;
  z-index: 9;
  .btn-submit {
    width: 100%;
  }
}
.footer-btns-edit {
	display: flex;
	justify-content: space-between;
  .btn-submit {
    width: 45%;
  }
}
</style>
